package com.hgs.iias.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.acegisecurity.context.SecurityContextHolder;

import com.hgs.iias.domain.Application;
import com.hgs.iias.domain.Enterprise;
import com.hgs.iias.service.ApplicationService;

public class ApplicationServiceImpl implements ApplicationService {
	@PersistenceContext
	private EntityManager em;
	
	public void apply(Application application) {
		application.setEnterprise(Enterprise.class.cast(SecurityContextHolder.getContext().getAuthentication().getPrincipal()));
		application.setStatus(Application.Status.SAVED);
		
		em.persist(application);
	}
	
	public List<Application> list() {
		List<Application> results = new ArrayList<Application>();
		
		for(Object o: em.createQuery("SELECT a FROM Application a").getResultList()) {
			results.add(Application.class.cast(o));
		}
		
		return results;
	}
	
	public void submit(Application application) {
		application.setStatus(Application.Status.SUBMITTED);
		
		em.merge(application);
	}
	
	public Application view(Long id) {
		return em.find(Application.class, id);
	}
}
